package controllers

import (
	"2302a_user/cache"
	"2302a_user/models"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "账号不能为空",
		}
		c.ServeJSON()
		return
	}
	user := models.User{
		Username: username,
		Password: password,
	}
	if err = user.GetUserByUsername(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}
	if user.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误 用户已重复",
		}
		c.ServeJSON()
		return
	}
	if err = user.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "注册失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "注册成功",
	}
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "账号不能为空",
		}
		c.ServeJSON()
		return
	}
	var user models.User
	user.Username = username
	user.Password = password
	if err = user.GetUserByUsername(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}
	key := "password_count_err" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count > 3 {
		cache.Rdb.Expire(cache.Ctx, key, time.Minute*5)
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误1",
		}
		c.ServeJSON()
		return
	}
	if user.Password != password {
		cache.Rdb.Incr(cache.Ctx, key)
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误2",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "登陆成功",
	}
	c.ServeJSON()
	return
}
